<?php
namespace Lib;

/**
 * FS--FileSystem
 * 文件及文件夹操作类
 *
 * @author shooke <QQ:82523829>
 */
class FS {
	/**
	 * 格式化大小函数
	 * @int $size 字节大小
	 * FS::formatsize($size);
	 */	
	public static function formatsize($size) {
		$prec=3;
		$size = round(abs($size));
		$units = array(0=>" B ", 1=>" KB", 2=>" MB", 3=>" GB", 4=>" TB");
		if ($size==0) return str_repeat(" ", $prec)."$units[0]";
		$unit = min(4, floor(log($size)/log(2)/10));
		$size = $size * pow(2, -10*$unit);
		$digi = $prec - 1 - floor(log($size)/log(10));
		$size = round($size * pow(10, $digi)) * pow(10, -$digi);
		return $size.$units[$unit];
	}
		
	/**
	 * 获取文件内容 读取文件
	 * 
	 * FS::read($filename);
	 */
	public static function read($filename) {
		$content = '';
		if(function_exists('file_get_contents')) {
			@$content = file_get_contents($filename);
		} else {
			if(@$fp = fopen($filename, 'r')) {
				@$content = fread($fp, filesize($filename));
				@fclose($fp);
			}
		}
		return $content;
	}
	
	/**
	 * 写入文件
	 *
	 * FS::write($filename, $writetext);
	 */
	public static function write($filename, $writetext, $openmod='w') {
	    $fp = fopen($filename, $openmod);
	    if($fp) {
			flock($fp, 2);
			fwrite($fp, $writetext);
			fclose($fp);
			return true;
		} else {	
			return false;
		}
	}
	
	/**
	 * 连续建目录 遍历创建目录
	 * 返回：顺利创建或者全部已建返回true，其它方式返回false
	 * @param unknown $dir
	 * @param number $mode
	 * @param string $recursive
	 * @return boolean|bool
	 */
	public static function mkdir( $dir, $mode = 0777, $recursive=true ) {
		if( ! $dir ) return false;
		$dir = str_replace( "\\", DIRECTORY_SEPARATOR, $dir );//处理分隔符
		if (file_exists($dir)) return true;//已存在返回true
		return mkdir($dir,$mode,$recursive);//返回创建状态
		
	}

	/**
	 * 遍历删除目录和目录下所有文件
	 * $root true删除指定目录 false删除指定目录下所有内容但不删除指定目录
	 * FS::rmdir($dir);
	 */
	public static function rmdir($dir,$root=true){	    
		if (!is_dir($dir)){
			return false;
		}
		$scan = self::scan($dir);
		foreach($scan as $val){
			is_dir($val) ? rmdir($val) : unlink($val);			
		}
		$root && rmdir($dir);		
	}
	
	public static function scan($path = '.') 
	{	
	    static $dir;
		$dirSep = DIRECTORY_SEPARATOR;
		$path = str_replace("\\",$dirSep,$path);
        $current_dir = opendir($path);    //opendir()返回一个目录句柄,失败返回false
        while(($file = readdir($current_dir)) !== false) {    //readdir()返回打开目录句柄中的一个条目
            $sub_dir = $path . $dirSep . $file;    //构建子目录路径
            if($file == '.' || $file == '..') {
                continue;
            } else if(is_dir($sub_dir)) {    //如果是目录,进行递归
                //echo 'Directory ' . $file . ':<br>';
                $dir[] = $sub_dir;
                call_user_func(['self','scan'], $sub_dir);
            } else {    //如果是文件,直接输出
                //echo 'File in Directory ' . $path . ': ' . $file . '<br>';
                $dir[] = $sub_dir;
            }
        }
        return $dir;
            
	}
	
	public static function getimg($path, &$files = array()){
		if (!is_dir($path)) return;
		$dir = self::scan($path);
		foreach($dir as $val){
			if (is_file($val) && preg_match("/\.(gif|jpeg|jpg|png|bmp)$/i", $file)) {
						$files[] = $path2;
					}
		}
		
		return $files;
	}
	/**
	 * 取得目录的目录大小、文件数、目录数
	 *
	 * @param unknown_type $path
	 * @return unknown
	 * 
	 * $path="/home/www/htdocs";
	   $ar=getDirectorySize($path);	 
	   echo "<h4>路径 : $path</h4>";
	   echo "目录大小 : ".sizeFormat($ar['size'])."<br>";
	   echo "文件数 : ".$ar['count']."<br>";
	   echo "目录术 : ".$ar['dircount']."<br>";
	 */
	public static function dirsize($path){
	  $totalsize = 0;
	  $totalcount = 0;
	  $dircount = 0;
	  $dir = self::scan($path);
	  foreach($dir as $val){
		  if(is_dir($val)){
			  $dircount++;
		  }else{
			  $totalsize += filesize ($val);
			  $totalcount++;
		  }
	  }
	  $total['size'] = $totalsize;
	  $total['count'] = $totalcount;
	  $total['dircount'] = $dircount;
	  return $total;
	}
}